package com.dex4d.update;

import android.app.Activity;
import android.support.annotation.Nullable;
import android.text.Html;
import android.widget.TextView;

import com.allenliu.versionchecklib.v2.AllenVersionChecker;
import com.allenliu.versionchecklib.v2.builder.UIData;
import com.allenliu.versionchecklib.v2.callback.RequestVersionListener;
import com.dex4d.BuildConfig;
import com.dex4d.R;
import com.dex4d.core.http.DefaultTransformer;
import com.dex4d.core.http.JsonApiWrapper;
import com.dex4d.utils.Log;
import com.tencent.bugly.beta.Beta;

/**
 * 作者    LiQingyi
 * 时间    2018/12/4 14:46
 * 文件    dex4d-android
 * 描述
 */
public class UpdateUtil {

    private Activity activity;

    public UpdateUtil(Activity activity) {
        this.activity = activity;
    }

    public void update() {

        JsonApiWrapper
                .serviceApi()
                .updateInfo(BuildConfig.UPDAE_URL_API)

                .compose(new DefaultTransformer<AppUpdate>())
                .subscribe(update -> {
                    check(update);
                }, throwable -> {
                    Log.i(throwable.getMessage());
                })
        ;

    }

    private void check(AppUpdate update) {
        AllenVersionChecker
                .getInstance()
                .requestVersion()
                .setRequestUrl(update.info)
                .request(new RequestVersionListener() {
                    @Nullable
                    @Override
                    public UIData onRequestVersionSuccess(String result) {
                        return crateUIData(update, result);
                    }

                    @Override
                    public void onRequestVersionFailure(String message) {

                    }
                })
                .setCustomVersionDialogListener((context, versionBundle) -> {
                    BaseDialog baseDialog = new BaseDialog(context, R.style.BaseDialog, R.layout.custom_dialog_one_layout);
                    TextView textView = baseDialog.findViewById(R.id.tv_msg);
                    textView.setText(Html.fromHtml(versionBundle.getContent()));
                    return baseDialog;
                })
                .executeMission(activity);
    }


    /**
     * @param update
     * @return
     */
    private UIData crateUIData(AppUpdate update, String info) {
        if (update.isUpdate(BuildConfig.VERSION_NAME)) {
            UIData uiData = UIData.create();
            uiData.setTitle(activity.getResources().getString(R.string.update_title));
            uiData.setDownloadUrl(update.url);
            //TODO 解析文字
            uiData.setContent(info);

            //放一些其他的UI参数，拿到后面自定义界面使用
            uiData.getVersionBundle().putString("key", "your value");

            return uiData;
        }
        return null;

    }

    public void cancel() {
        AllenVersionChecker.getInstance().cancelAllMission(activity);
    }

}
